// 写病友圈
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import request from '../../api/request'
import {
  Button,
  DatePicker,
  Grid,
  ImageUploader,
  Input,
  Switch,
  TextArea,
  Toast,
} from 'antd-mobile'
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import TopHeader from '../../components/TopHeader'
import './Post.css'

interface Department {
  id: number
  departmentName: string
}

const MAX_TITLE = 20
const MAX_DETAIL = 300

// 固定的主要病症列表（独立于科室）
const DISEASE_LIST: string[] = [
  '猩红热', '百日咳', '水痘', '风疹', '麻疹', '儿童骨髓炎', '儿童风湿热', '小儿肾炎',
  '小儿遗尿症', '小儿夜哭', '婴儿肠胃炎', '儿童便秘', '儿童肝炎', '哮喘', '儿童缺铁性贫血', '新生儿黄疸'
]

/* 固定的就诊科室（仅用于下拉展示，模拟数据）
const DEPARTMENT_LIST: Department[] = [
  { id: 1, departmentName: '内科' },
  { id: 2, departmentName: '骨科' },
  { id: 3, departmentName: '眼科' },
  { id: 4, departmentName: '小儿科' },
  { id: 5, departmentName: '急诊科' },
  { id: 6, departmentName: '皮肤性病' },
  { id: 7, departmentName: '耳鼻喉科' },
  { id: 8, departmentName: '精神病科' },
]; */

const PatientCirclePost = () => {
  const navigate = useNavigate()
  const [departments, setDepartments] = useState<Department[]>([])

  // 基本表单
  const [title, setTitle] = useState('')
  const [departmentId, setDepartmentId] = useState<number | undefined>()
  const [disease, setDisease] = useState('')
  const [detail, setDetail] = useState('')

  // 下拉开关
  const [showDeptSelector, setShowDeptSelector] = useState(false)
  const [showDiseaseSelector, setShowDiseaseSelector] = useState(false)

  // 经历
  const [treatmentHospital, setTreatmentHospital] = useState('')
  const [treatmentStartTime, setTreatmentStartTime] = useState<string>('')
  const [treatmentEndTime, setTreatmentEndTime] = useState<string>('')
  const [treatmentProcess, setTreatmentProcess] = useState('')

  // 图片上传（仅布局，真实上传对接后端时替换 upload）
  const [images, setImages] = useState<ImageUploadItem[]>([])
  const [pendingFiles, setPendingFiles] = useState<File[]>([])

  // 悬赏
  const [raiseAmount, setRaiseAmount] = useState(false)
  const [amount, setAmount] = useState<number>(0)
  const [useCustomAmount, setUseCustomAmount] = useState<boolean>(false)
  const presetAmounts = [10, 20, 30]
  const balance = 300

  // 日期选择
  const [pickerVisible, setPickerVisible] = useState<null | 'start' | 'end'>(null)
  const pickerValue = useMemo(() => {
    const current = pickerVisible === 'start' ? treatmentStartTime : treatmentEndTime
    return current ? new Date(current) : new Date()
  }, [pickerVisible, treatmentStartTime, treatmentEndTime])

  const selectedDepartmentName = useMemo(() => {
    return departments.find(d => d.id === departmentId)?.departmentName || ''
  }, [departments, departmentId])

  // 下拉科室数据：从后端获取真实科室
  useEffect(() => {
    const fetchDepartments = async () => {
      try {
        const res: any = await request.get('/health/share/knowledgeBase/v1/findDepartment')
        if (res?.result && Array.isArray(res.result)) {
          setDepartments(res.result)
        }
      } catch (err) {
        console.error('获取科室失败', err)
        Toast.show({ content: '获取科室失败，请稍后重试' })
      }
    }
    fetchDepartments()
  }, [])

  const validate = (): string | null => {
    if (!title.trim()) return '请输入标题'
    if (title.trim().length > MAX_TITLE) return '标题不超过20字'
    if (!departmentId) return '请选择就诊科室'
    if (!disease.trim()) return '请选择主要病症或手动输入'
    if (!detail.trim()) return '请输入病症详情'
    if (treatmentStartTime && treatmentEndTime && treatmentStartTime > treatmentEndTime)
      return '开始时间不能晚于结束时间'
    return null
  }

  const onSubmit = async () => {
    const err = validate()
    if (err) {
      Toast.show({ content: err })
      return
    }

    console.log('开始提交表单...')
    console.log('表单数据:', {
      title,
      departmentId,
      disease,
      detail,
      treatmentHospital,
      treatmentStartTime,
      treatmentEndTime,
      treatmentProcess,
      raiseAmount,
      amount,
      imagesCount: images.length
    })

    try {
      // 图片在发布成功后再逐张上传（此处不处理 imageUrls）
      // 构建JSON请求体（图片不在这里提交）
      const requestBody = {
        title: title.trim(),
        departmentId: departmentId,
        disease: disease.trim(),
        detail: detail.trim(),
        treatmentHospital: treatmentHospital.trim() || null,
        treatmentStartTime: treatmentStartTime || null,
        treatmentEndTime: treatmentEndTime || null,
        treatmentProcess: treatmentProcess.trim() || null,
        amount: raiseAmount ? (amount || 0) : 0,
      }

      console.log('请求体:', requestBody)

      const resp: any = await request.post('/health/user/sickCircle/verify/v1/publishSickCircle', requestBody)
      console.log('发布成功:', resp)

      // 兼容多种返回结构，尽力拿到 sickCircleId
      const sickCircleId = resp?.result?.sickCircleId || resp?.sickCircleId || resp?.result?.id || resp?.id

      // 如果有图片需要上传且拿到了 sickCircleId，则逐张上传
      if (sickCircleId && pendingFiles.length > 0) {
        for (const file of pendingFiles) {
          const formData = new FormData()
          formData.append('sickCircleId', String(sickCircleId))
          formData.append('picture', file)
          await request.post('/health/user/sickCircle/verify/v1/uploadSickCirclePicture', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          })
        }
        // 清空本地待上传文件
        setPendingFiles([])
      }

      Toast.show({ content: '发布成功' })
      navigate('/patient-circle')
    } catch (e: any) {
      console.error('发布失败', e)
      let errorMessage = '发布失败，请稍后重试'

      // 处理具体的错误信息
      if (e?.response?.data?.message) {
        errorMessage = e.response.data.message
      } else if (e?.response?.status === 400) {
        errorMessage = '请求参数错误，请检查输入信息'
      } else if (e?.response?.status === 401) {
        errorMessage = '登录已过期，请重新登录'
      }

      Toast.show({ content: errorMessage })
    }
  }

  // 真实的图片上传功能
  const localPreviewUpload = async (file: File): Promise<{ url: string }> => {
    // 收集文件，返回本地预览地址，仅做占位展示，真正上传在提交后执行
    setPendingFiles(prev => [...prev, file])
    return { url: URL.createObjectURL(file) }
  }

  // 处理图片删除
  const handleImageDelete = (item: ImageUploadItem): boolean => {
    const index = images.findIndex(img => img.url === item.url)
    if (index > -1) {
      const newImages = [...images]
      newImages.splice(index, 1)
      setImages(newImages)
    }
    return true
  }

  return (
    <div className="post-page">
      <TopHeader />
      <div className="section">
        <div className="field">
          <div className="label required">
            <Input
              value={title}
              onChange={val => setTitle(val)}
              maxLength={MAX_TITLE}
              placeholder="请输入标题(最多20个字)"
              clearable
            />
          </div>
        </div>

        {/* 请选择就诊科室 - 可折叠 */}
        <div className="field">
          <div className="selector-header" onClick={() => setShowDeptSelector(v => !v)}>
            <div className="label required">
              {selectedDepartmentName ? selectedDepartmentName : '请选择就诊科室'}
            </div>
            <div className={`arrow ${showDeptSelector ? 'open' : ''}`}>▲</div>
          </div>
          {showDeptSelector && (
            <div className="selector-panel">
              <Grid columns={4} gap={12}>
                {departments.map(d => (
                  <Grid.Item key={d.id}>
                    <div
                      className={`tag ${departmentId === d.id ? 'active' : ''}`}
                      onClick={() => { setDepartmentId(d.id); setShowDeptSelector(false) }}
                    >
                      {d.departmentName}
                    </div>
                  </Grid.Item>
                ))}
              </Grid>
            </div>
          )}
        </div>

        {/* 请选择主要病症 - 与就诊科室一致样式 */}
        <div className="field">
          <div className="selector-header" onClick={() => setShowDiseaseSelector(v => !v)}>
            <div className="label required">
              {disease ? disease : '请选择主要病症'}
            </div>
            <div className={`arrow ${showDiseaseSelector ? 'open' : ''}`}>▲</div>
          </div>
          {showDiseaseSelector && (
            <div className="selector-panel">
              <Grid columns={4} gap={12}>
                {DISEASE_LIST.map(v => (
                  <Grid.Item key={v}>
                    <div
                      className={`tag ${disease === v ? 'active' : ''}`}
                      onClick={() => { setDisease(v); setShowDiseaseSelector(false) }}
                    >
                      {v}
                    </div>
                  </Grid.Item>
                ))}
              </Grid>
            </div>
          )}
        </div>

        <div className="field">
          <div className="label required">请输入病症详情</div>
          <TextArea
            value={detail}
            onChange={val => setDetail(val)}
            maxLength={MAX_DETAIL}
            placeholder="请输入"
            rows={6}
            showCount
          />
          <div className="hint">不超过{MAX_DETAIL}字</div>
        </div>
      </div>

      <div className="section">
        <div className="section-title">请输入最近一段治疗经历</div>

        <div className="field">
          <div className="label">输入医院名称</div>
          <Input
            value={treatmentHospital}
            onChange={val => setTreatmentHospital(val)}
            placeholder="请输入医院名称"
            clearable
          />
        </div>

        <div className="row-2">
          <div className="field">
            <div className="label">选择开始时间</div>
            <div className="picker-input" onClick={() => setPickerVisible('start')}>
              {treatmentStartTime || '请选择'}
            </div>
          </div>
          <div className="field">
            <div className="label">选择结束时间</div>
            <div className="picker-input" onClick={() => setPickerVisible('end')}>
              {treatmentEndTime || '请选择'}
            </div>
          </div>
        </div>

        {/* 日期选择弹窗，使用DatePicker自带的弹窗而非自定义Popup，避免遮罩冲突 */}
        <DatePicker
          visible={!!pickerVisible}
          precision="day"
          value={pickerValue}
          onClose={() => setPickerVisible(null)}
          onConfirm={date => {
            const str = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
              date.getDate()
            ).padStart(2, '0')}`
            if (pickerVisible === 'start') setTreatmentStartTime(str)
            if (pickerVisible === 'end') setTreatmentEndTime(str)
            setPickerVisible(null)
          }}
        />

        <div className="field">
          <TextArea
            value={treatmentProcess}
            onChange={val => setTreatmentProcess(val)}
            placeholder="请输入治疗过程描述"
            rows={5}
          />
        </div>
      </div>

      <div className="section">
        <div className="section-title">最多可添加6张图片；长按为图片排序</div>
        <ImageUploader
          value={images}
          onChange={setImages}
          upload={localPreviewUpload}
          onDelete={handleImageDelete}
          maxCount={6}
          showUpload={images.length < 6}
        />
      </div>

      <div className="section">
        <div className="raise-row">
          <div className="raise-title">提升悬赏额度</div>
          <Switch
            checked={raiseAmount}
            onChange={(v) => {
              setRaiseAmount(v)
              if (v) {
                setUseCustomAmount(false)
                setAmount(presetAmounts[0])
              } else {
                setAmount(0)
              }
            }}
          />
        </div>
        <div>提升额度可获得更多关注、得到更多建议</div>
        {raiseAmount && (
          <div className="field" style={{ marginTop: 8 }}>
            <Grid columns={3} gap={12}>
              {presetAmounts.map((pa) => (
                <Grid.Item key={pa}>
                  <div
                    className={`amount-card ${!useCustomAmount && amount === pa ? 'active' : ''}`}
                    onClick={() => {
                      setUseCustomAmount(false)
                      setAmount(pa)
                    }}
                  >
                    {pa}H币
                  </div>
                </Grid.Item>
              ))}
              <Grid.Item>
                <div
                  className={`amount-card ${useCustomAmount ? 'active' : ''}`}
                  onClick={() => setUseCustomAmount(true)}
                >
                  自定义
                </div>
              </Grid.Item>
            </Grid>

            {useCustomAmount && (
              <div style={{ marginTop: 12 }}>
                <Input
                  type="number"
                  value={amount ? String(amount) : ''}
                  onChange={(val) => setAmount(Number(val || 0))}
                  placeholder="请输入悬赏金额"
                />
              </div>
            )}

            <div style={{ marginTop: 12, color: '#666' }}>
              当前H币余额 <b style={{ color: '#333' }}>{balance}</b>。不足?{' '}
              <a href="#" onClick={(e) => { e.preventDefault(); Toast.show({ content: '前往充值' })}}>去充值</a>
            </div>
          </div>
        )}
      </div>

      <div className="submit-box">
        <Button block color="primary" size="large" onClick={onSubmit}>
          发表
        </Button>
      </div>
    </div>
  )
}

export default PatientCirclePost